package com.tjsinfo.tjsoa.efile.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ResourceBundle;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.tjsinfo.tjsoa.common.ToolKit;
import com.tjsinfo.tjsoa.efile.dao.IEfileDao;
import com.tjsinfo.tjsoa.efile.vo.Efile;
import com.tjsinfo.tjsoa.mail.dao.ITjsAnnexDao;
import com.tjsinfo.tjsoa.mail.dao.ITjsDeleteEmailAnnexDAO;
import com.tjsinfo.tjsoa.mail.dao.ITjsDrefAnnexDao;
import com.tjsinfo.tjsoa.mail.dao.ITjsFoldEmailAnnexDAO;
import com.tjsinfo.tjsoa.mail.vo.TjsAnnex;


public class EfileAction extends Action {
	private IEfileDao efileDao;
	
	public IEfileDao getEfileDao() {
		return efileDao;
	}

	public void setEfileDao(IEfileDao efileDao) {
		this.efileDao = efileDao;
	}

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		String url = "error";

		String toFilePath = ToolKit.getProperties("com/tjsinfo/tjsoa/efile/properties/systemResource.properties", this).getProperty("efile.toFileUrl");
		// TODO Auto-generated method stub
		try {
			Integer id=Integer.valueOf(request.getParameter("id"));
			Efile expressFile = efileDao.findById(id);
			File file = new File(toFilePath+expressFile.getFileName()); 			
			InputStream fis = new BufferedInputStream(new FileInputStream(toFilePath+expressFile.getFileName()));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();		
			response.reset();
		    response.addHeader("Content-Disposition", "attachment;filename=" + new String(expressFile.getCfileName().getBytes("GBK"),"ISO8859-1"));
	        response.addHeader("Content-Length", "" + file.length());
	        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
	        response.setContentType("application/octet-stream");
	        toClient.write(buffer);
	        toClient.flush();
	        toClient.close();
			url = "ok";
		} catch (IOException ex) {
			request.setAttribute("returnSting", "服务器忙，请稍后下载！");
			ex.printStackTrace();
			return mapping.findForward("error");
		} catch(NullPointerException ex){
			return null;
		} catch (Exception ex){
			request.setAttribute("returnSting", "服务器忙，请稍后下载！");
			return mapping.findForward("error");
		}
		if ("ok".equals(url)) {
			return null;	
		}else {
			request.setAttribute("returnSting", "服务器忙，请稍后下载！");
			return  mapping.findForward(url);
		}
	}
}
